var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];

$(window).load(function() {
	
	$(".scroll").niceScroll();
	
	$(".dropdown dt a").click(function() {
			// Change the behaviour of onclick states for links within the menu.
		var toggleId = "#" + this.id.replace(/^link/,"ul");
			// Hides all other menus depending on JQuery id assigned to them
		$(".dropdown dd ul").not(toggleId).hide();
			//Only toggles the menu we want since the menu could be showing and we want to hide it.
		$(toggleId).toggle();
			//Change the css class on the menu header to show the selected class.
		if($(toggleId).css("display") == "none"){
			$(this).removeClass("selected");
		}else{
			$(this).addClass("selected");
		}
	});

	$(".dropdown dd ul li a").click(function() {

		// This is the default behaviour for all links within the menus
		var text = $(this).html();
		$(".dropdown dt a span").html(text);
		$(".dropdown dd ul").hide();
	});

	$(document).bind('click', function(e) {
		// Lets hide the menu when the page is clicked anywhere but the menu.
		var $clicked = $(e.target);
		if (! $clicked.parents().hasClass("dropdown")){
			$(".dropdown dd ul").hide();
			$(".dropdown dt a").removeClass("selected");
		}

	});
	
	$('#slider').jcarousel({
		visible: 1,
		auto: 5,
		scroll: 1,
		wrap: "both",
		animation: 800,
		easing: 'easeInOutExpo',
		initCallback: slider_initCallback,
		itemFirstInCallback: slider_itemFirstInCallback
	});
	
	if($('.player').length) {
		setTimeout(function() {
			$('.player').hide();
		}, 1000);
	}

	$('.field, textarea').focus(function() {
        if(this.title==this.value) {
            this.value = '';
        }
    }).blur(function(){
        if(this.value=='') {
            this.value = this.title;
        }
    });
    
    $('.fancybox').fancybox();

	$('textarea').autogrow();
	
    var austDay = new Date();
    var date_str = $('header .next h4').text().replace(',', '').split(' ');

    var month_str = date_str[0];
    for(i=0;i<months.length;i++) {
    	if(months[i] == month_str) {
    		var austMonth = i;
    	}
    }
    var austDate = parseInt(date_str[1]);
    var austYear = parseInt(date_str[2]);

	austDay = new Date(austYear, austMonth, austDate);
	$('header .next h4').html('<span>in</span> <span class="container" />').find('.container').countdown({until: austDay});

	$('#slider .button').click(function() {
		if($(this).text().indexOf('Audio') != -1) {
			$(this).parent().find('.player').slideDown(function() {
				$(this).find('.APV1_play_button').trigger('click');
			});
			if($.browser.msie) {
				$(this).hide();
			} else {
				$(this).fadeOut();
			}
			return false;
		} else if($(this).text().indexOf('Video') != -1) {
			if($(this).parent().find('.url').attr('rel') == 'youtube') {
				var vid_string = $(this).parent().find('.url').text();
				var vid_html = '<iframe width="100%" height="408" src="http://www.youtube.com/embed/' + vid_string + '?rel=0&amp;autoplay=1&amp;wmode=transparent&amp;hd=1" frameborder="0"></iframe>'
			} else if($(this).parent().find('.url').attr('rel') == 'vimeo') {
				var vid_string = $(this).parent().find('.url').text();
				var vid_html = '<iframe src="http://player.vimeo.com/video/' + vid_string + '?autoplay=1&amp;title=0&amp;byline=0&amp;portrait=0" width="100%" height="408" frameborder="0"></iframe>';
			}
			$(this).fadeOut();
			$(this).parent().css('background', '#000').find('.caption').animate({
				bottom: '-100px'
			}, 200, function() {
				$(this).parent().find('img').fadeOut(function() {
					$(this).parent().append(vid_html);
					//$(this).remove();
				});
				//$(this).remove();
			});
			return false;
		}
	});

	if($('article .image').length) {
		$('article .image').each(function() {
			$(this).append('<span class="corner-tl" /><span class="corner-tr" /><span class="corner-bl" /><span class="corner-br" />');
		});
	}
	
	if($('.gallery .image').length) {
		$('.gallery .image').each(function() {
			var randomNumber = Math.floor(Math.random()*3);
			var subRandomNumber = Math.floor(Math.random()*3);
			randomNumber = randomNumber - subRandomNumber;
			$(this).css('-webkit-transform','rotate('+randomNumber+'deg)');
			$(this).css('-moz-transform','rotate('+randomNumber+'deg)');
		});
	}

	if($.browser.msie && $.browser.version < 8) {
		$('html').css('overflow-x', 'hidden');
	}
	
	$('.jcarousel-next, .jcarousel-prev').click(function(){
		
		// Get the current slide's position
		var currentSlidePosition = $('#slider').find('ul').position();
		currentSlidePosition = ((currentSlidePosition.left * -1) / 940);
	
		// Get the current slide
		var currentSlide = $('.jcarousel-item').eq(currentSlidePosition);
		
		// Hide the audio player
		currentSlide.find('.player').hide();
		currentSlide.find('.APV1_playing').find('.APV1_play_button').trigger('click');
		
		// Hide the video player
		currentSlide.find('iframe').remove();
		currentSlide.find('img').fadeIn();
		
		// Show the button
		currentSlide.find('.button').show();
		
	});
	
	if($('article .image').length && $.browser.msie) {
		$('article .image').each(function() {
			$(this).css('width', $(this).find('img').width());
		});
	}
	
})

window.autoScrollPermOff = false;

function slider_initCallback(carousel) {
	if($('#slider span.url').length) {
		$('#slider span.url').each(function() {
			if($(this).text().indexOf('www.') != -1) {
				var remove_www = $(this).text().toString().replace('www.', '');
				$(this).text(remove_www);
			}
			if($(this).text().indexOf('youtube') != -1) {
				$(this).attr('rel', 'youtube');
				var replaced_string = $(this).text().toString().replace('http://youtube.com/watch?v=', '');
				$(this).text(replaced_string);
			} else if($(this).text().indexOf('vimeo') != -1) {
				$(this).attr('rel', 'vimeo');
				var replaced_string = $(this).text().toString().replace('http://vimeo.com/', '');
				$(this).text(replaced_string);
			}
		});
	}
	
	var autoPermOff = false;
	
	// Stop autoscrolling when a button is clicked
	carousel.clip.find('.button').click(function(){
		carousel.stopAuto();
		autoPermOff = true;
	});
	
    // Pause autoscrolling if the user moves with the cursor over the clip.
    carousel.clip.hover(function() {
        carousel.stopAuto();
    }, function() {
    	if (!autoPermOff) {
    		carousel.startAuto();
    	}
    });

	$('.jcarousel-prev, .jcarousel-next').append('<span class="icon" />');
}

function slider_itemFirstInCallback(carousel, item, idx, state) {
	$('#slider .jcarousel-list > li .caption').css('bottom', '-100px');
	$('#slider .jcarousel-list > li').eq(idx-1).find('.caption').animate({
		bottom: '0px'
	}, 500, 'easeOutQuint');
}

/**************************************************
 *                      Menu GMap
 **************************************************/
 
function Menu($div){
  var that = this, 
      ts = null;
  
  this.$div = $div;
  this.items = [];
  
  // create an item using a new closure 
  this.create = function(item){
    var $item = $('<div class="item '+item.cl+'">'+item.label+'</div>');
    $item
      // bind click on item
      .click(function(){
        if (typeof(item.fnc) === 'function'){
          item.fnc.apply($(this), []);
        }
      })
      // manage mouse over coloration
      .hover(
        function(){$(this).addClass('hover');},
        function(){$(this).removeClass('hover');}
      );
    return $item;
  };
  this.clearTs = function(){
    if (ts){
      clearTimeout(ts);
      ts = null;
    }
  };
  this.initTs = function(t){
    ts = setTimeout(function(){that.close()}, t);
  };
}

// add item
Menu.prototype.add = function(label, cl, fnc){
  this.items.push({
    label:label,
    fnc:fnc,
    cl:cl
  });
}

// close previous and open a new menu 
Menu.prototype.open = function(event){
  this.close();
  var k,
      that = this,
      offset = {
        x:0, 
        y:0
      },
      $menu = $('<div id="menu"></div>');
      
  // add items in menu
  for(k in this.items){
    $menu.append(this.create(this.items[k]));
  }
  
  // manage auto-close menu on mouse hover / out
  $menu.hover(
    function(){that.clearTs();},
    function(){that.initTs(3000);}
  );
  
  // change the offset to get the menu visible (#menu width & height must be defined in CSS to use this simple code)
  if ( event.pixel.y + $menu.height() > this.$div.height()){
    offset.y = -$menu.height();
  }
  if ( event.pixel.x + $menu.width() > this.$div.width()){
    offset.x = -$menu.width();
  }
  
  // use menu as overlay
  this.$div.gmap3({
    action:'addOverlay',
    latLng: event.latLng,
    content: $menu,
    offset: offset
  });
  
  // start auto-close
  this.initTs(5000);
}

// close the menu
Menu.prototype.close = function(){
  this.clearTs();
  this.$div.gmap3({action:'clear', name:'overlay'})
}